package com.dx.as.upload;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.BufferedSink;

/**
 * Created by jwaoo on 2017/7/17.
 */

public class ProgressRequestBody extends RequestBody {
    private File mFile;
    private static final int DEFAULT_BUFFER_SIZE = 2048;
    private int msgId = 0;
    private DownloadInfo downloadInfo;
    public ProgressRequestBody(final File file,int msgId,DownloadInfo downloadInfo) {
        this.downloadInfo = downloadInfo;
        DownloadManager.addDownload(msgId,downloadInfo);
        mFile = file;
        this.msgId = msgId;
    }

    @Override
    public MediaType contentType() {
        // i want to upload only images
        return MediaType.parse("video/mp4");
    }

    @Override
    public void writeTo(BufferedSink sink) throws IOException {
        long fileLength = mFile.length();
        byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
        FileInputStream in = new FileInputStream(mFile);
        long uploaded = 0;
        try {
            int read;
            while ((read = in.read(buffer)) != -1) {
                uploaded += read;
                sink.write(buffer, 0, read);
                // update progress on UI thread
//                this.downloadInfo.onDownProgress(uploaded,  fileLength);

                DownloadManager.getDownloadObject(this.msgId).onDownProgress(uploaded,  fileLength);
            }
            DownloadManager.getDownloadObject(this.msgId).onDownLoadSuccess();
        }catch (Exception ex) {
            ex.printStackTrace();
            DownloadManager.getDownloadObject(this.msgId).onDownLoadFailed();
        }finally {
            try{
                in.close();
            }catch (Exception ex){
                ex.printStackTrace();
            }
        }
    }

}
